package cn.haoxsf.app.system.controller;


import cn.haoxsf.app.common.api.CommonResult;
import cn.haoxsf.app.common.api.enums.SystemExceptionEnum;
import cn.haoxsf.app.common.apo.repeat.Submit;
import cn.haoxsf.app.common.util.ToolUtil;
import cn.haoxsf.app.common.util.ValidatedUtil;
import cn.haoxsf.app.system.entity.Member;
import cn.haoxsf.app.system.model.param.RegisterParam;
import cn.haoxsf.app.system.service.IAuthService;
import cn.haoxsf.app.system.service.IBusinessService;
import cn.haoxsf.app.system.service.IMemberService;
import io.swagger.annotations.*;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.http.HttpServletResponse;


/**
 * <p>
 * 后台用户表 前端控制器
 * </p>
 *
 * @author Ele  qvbanfm@qq.com
 * @since 2020-01-07
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户相关请求", description = "UserController")
@Log4j2
public class UserController {
    @Autowired
    private IAuthService authService;
    @Autowired
    private IMemberService memberService;
    @Autowired
    private IBusinessService businessService;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;



    @PostMapping("/register")
    @ApiOperation(value = "用户注册", notes = "")
    @Submit
    public CommonResult register(HttpServletResponse response,@RequestBody(required = false) @ApiParam(value = "注册JSON参数") @Validated RegisterParam registerParam, BindingResult result) {
        if (ToolUtil.isEmpty(registerParam)) {
            return CommonResult.error(SystemExceptionEnum.VALIDATE_FAILED.getCode(), SystemExceptionEnum.VALIDATE_FAILED.getMsg() + "用户名或者密码为空");
        }
        if (result.hasErrors()) {
            String errorMessage = ValidatedUtil.getErrorMessage(result);
            return CommonResult.error(SystemExceptionEnum.VALIDATE_FAILED.getCode(), errorMessage);
        }
        Member member = new Member();
        member.setOpenId(ToolUtil.isEmpty(registerParam.getOpenId())? null:registerParam.getOpenId());
        BeanUtils.copyProperties(registerParam, member);
        member.setLatitude(Double.valueOf(registerParam.getLatitude()));
        member.setLongitude(Double.valueOf(registerParam.getLongitude()));
        member.setPhone(registerParam.getPhone());
        if(!"6668".equals(registerParam.getSms())){
            return CommonResult.error(SystemExceptionEnum.VALIDATE_FAILED.getCode(),"验证码错误！");
        }
        memberService.add(member);
        String loginToken = authService.login(registerParam.getUsername(), registerParam.getPassword());
        response.setHeader(tokenHeader,tokenHead+" "+loginToken);
        return CommonResult.success();
    }

    @GetMapping("get")
    @ApiOperation(value = "获取用户信息", notes = "")
    public CommonResult get() {
        String username = authService.getLoginUser().getUsername();
        return CommonResult.success(memberService.getMemberAndBusinessByUsername(username));
    }


    @ApiOperation(value = "用于师傅改变开工状态;    OPEN=开工；OFF=收工 ;注意需要师傅的权限", notes = "传参格式：{ 'state': 'OFF' }")
    @PostMapping("/change")
    @PreAuthorize("hasAuthority('xsf:bus:yes')")
    @Submit
    public CommonResult changeState(@RequestBody String state) {
        JSONObject jsonObject = JSON.parseObject(state);
        if (ToolUtil.isEmpty(jsonObject)) {
            return CommonResult.error(404, "参数为空！或者json参数不正确！");
        }

        Object status = jsonObject.get("state");
        if (ToolUtil.isEmpty(status)) {
            return CommonResult.error(404, "json参数不正确！");
        }
        String string = status.toString();
        if ("OPEN".equals(string) || "OFF".equals(string)) { //TODO 关键字的判断 后面要查询字典
            businessService.changeWorkState(authService.getLoginUser().getId(), string);
            return CommonResult.success();
        } else {
            return CommonResult.error(SystemExceptionEnum.VALIDATE_FAILED);
        }
    }


}
